import java.util.ArrayList;
import java.util.List;

public class num556 {
    public int nextGreaterElement(int n) {
        List<Integer> list = new ArrayList<>();
        while (n > 0) {
            list.add(n % 10);
            n = n / 10;
        }
        int index = -1;
        for (int i = 0; i < list.size() - 1 && index == -1; i++) {
            if(list.get(i + 1) < list.get(i)) {
                index = i + 1;
            }
        }
        if(index == -1) {
            return index;
        }
        for (int i = 0; i < index; i++) {
            if(list.get(i) > list.get(index)) {
                swap(list,i,index);
                break;
            }
        }
        int l = 0;
        int r = index - 1;
        while (l < r) {
            swap(list,l,r);
            l ++;
            r --;
        }
        long ans = 0;
        for (int i = list.size() - 1; i >= 0; i--) {
            ans = ans * 10 + list.get(i);
        }
        return ans > Integer.MAX_VALUE? -1 : (int) ans;
    }

    private void swap(List<Integer> list, int i, int index) {
        int temp = list.get(i);
        list.set(i, list.get(index));
        list.set(index,temp);
    }
}
